<template>
  <div class="app-container">
    <!-- 表格 -->
    <el-table
      :key="tableKey"
      ref="table"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="排序" prop="order" align="center" width="50" />
      <el-table-column label="商品名称" header-align="center" width="150">
        <template slot-scope="{ row }">
          <el-image
            style="width: 40px; height: 40px;text-align: center;"
            :src="$store.state.settings.imgHost + row.image"
            :preview-src-list="[$store.state.settings.imgHost + row.image]"
          />
          <span style="vertical-align: top;margin-left: 10px;">{{
            row.name
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" prop="price" align="center" />
      <el-table-column label="商品分类" align="center">
        <template slot-scope="{ row }">{{
          row.type == 0 ? "首次上架" : row.type == 1 ? "续拍商品" : ""
        }}</template>
      </el-table-column>
      <el-table-column
        label="店铺"
        align="center"
        prop="shopping.shopping_name"
      />
      <el-table-column
        align="center"
        label="创建时间"
        prop="created_at"
        width="170"
      />
      <el-table-column label="操作" align="center" width="250">
        <template slot-scope="{ row }">
          <!-- <el-button
            v-if="row.status == 1 && row.audit_status == 3"
            size="mini"
            plain
            type="success"
            @click="handleEdit(row, 1)"
          >
            上拍
          </el-button> -->
          <el-button
            size="mini"
            plain
            type="primary"
            @click="handleEdit(row, '')"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            plain
            type="danger"
            @click="handleDelete(row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div v-if="total > 0" style="text-align: right;">
      <pagination
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.per_page"
        @pagination="getList"
      />
    </div>

    <!-- 编辑 -->
    <el-dialog
      title="编辑"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="60%"
    >
      <div style="text-align: center;">
        <el-radio-group v-model="radioValue">
          <el-radio-button label="基础信息" />
          <el-radio-button label="商品详情" />
        </el-radio-group>
      </div>
      <div v-show="radioValue == '基础信息'" style="margin-top: 20px;">
        <el-form
          ref="postForm"
          :model="form"
          :rules="rules"
          class="form-container"
        >
          <div class="createPost-main-container">
            <el-form-item label-width="90px" label="拍品名称:" prop="name">
              <el-input v-model.trim="form.name" />
            </el-form-item>
            <el-form-item
              label-width="90px"
              label="拍品分类:"
              prop="product_category_id"
            >
              <el-select
                v-model="form.product_category_id"
                placeholder="请选择拍品分类"
                clearable
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in classifyOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label-width="90px" label="起拍价:" prop="price">
              <el-input v-model="form.price" class="input-spin" type="number" />
            </el-form-item>
            <el-form-item label="拍品主图:" label-width="90px" prop="image">
              <!-- <img
                style="width:148px;height:148px;display:inline-block;margin-right:8px;margin-bottom:8px"
                :src="form.image"
              /> -->
              <el-upload
                :show-file-list="false"
                action="#"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                list-type="picture-card"
                :http-request="
                  file => {
                    return uploadOneImgHandle(file, 'form');
                  }
                "
              >
                <img
                  style="width:100%;height:100%"
                  v-if="form.image"
                  :src="form.image"
                />
                <i class="el-icon-plus" v-else />
              </el-upload>
            </el-form-item>
            <el-form-item label-width="90px" label="拍品图片:" prop="image">
              <el-upload
                :file-list="fileList"
                action="#"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                list-type="picture-card"
                :http-request="
                  file => {
                    return uploadImgHandle(file, 'form');
                  }
                "
                :on-remove="
                  (file, fileList) => {
                    return removeHandle(file, fileList, 'form');
                  }
                "
              >
                <i class="el-icon-plus" />
              </el-upload>
            </el-form-item>
            <div class="el-form-item-cust">
              <div class="label">拍品参数:</div>
              <div class="el-form-items">
                <el-button size="small" icon="el-icon-plus" @click="addParam"
                  >添加</el-button
                >
                <div
                  class="el-form-item__error"
                  style="top:0"
                  v-if="paramsNoSet"
                >
                  拍品参数未设置
                </div>
              </div>
            </div>

            <div class="el-form-item-cust">
              <div class="label"></div>
              <div class="el-form-items">
                <el-row
                  style="width:600px"
                  :gutter="1"
                  v-for="(item, index) in form._params"
                  :key="index"
                >
                  <el-col :span="9">
                    <el-form-item
                      :prop="'_params.' + index + '.model'"
                      :rules="paramsRules.model"
                    >
                      <el-input v-model="item.model" placeholder="参数名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="9">
                    <el-form-item
                      :prop="'_params.' + index + '.value'"
                      :rules="paramsRules.value"
                    >
                      <el-input v-model="item.value" placeholder="参数内容" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="2"
                    ><span class="del" @click="delParam(index)"
                      >删除</span
                    ></el-col
                  >
                </el-row>
              </div>
            </div>

            <el-form-item label-width="90px" label="排序:">
              <el-input v-model="form.order" class="input-spin" type="number" />
            </el-form-item>
            <el-form-item label-width="90px" label="店铺:">
              <el-input v-model.trim="form.shopping_name" disabled />
            </el-form-item>
            <el-form-item label-width="90px" label="创建时间:">
              <el-date-picker
                v-model="form.created_at"
                type="datetime"
                placeholder="选择创建时间"
                :clearable="false"
                style="width: 100%;"
                disabled
              />
            </el-form-item>
            <el-form-item label-width="90px" label="会员:">
              <el-input v-model.trim="form.user_info" disabled />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div v-show="radioValue == '商品详情'" style="margin-top: 20px;">
        <Tinymce ref="editor" v-model="form.content" :height="400" />
      </div>
      <div style="margin-top: 40px;text-align: center;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleSubmit">保存</el-button>
      </div>
    </el-dialog>

    <!-- 上拍 -->
    <el-dialog
      title="上拍"
      :visible.sync="dialogVisible1"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="60%"
    >
      <div style="margin-top: 20px;">
        <el-form
          ref="postForm1"
          :model="form1"
          :rules="rules"
          class="form-container"
          label-width="100px"
        >
          <div class="createPost-main-container">
            <el-form-item label="排序:">
              <el-input
                v-model="form1.order"
                disabled
                class="input-spin"
                type="number"
              />
            </el-form-item>
            <el-form-item label="拍品名称:" prop="name">
              <el-input v-model.trim="form1.name" disabled />
            </el-form-item>
            <el-form-item label="拍品分类:" disabled prop="product_category_id">
              <el-select
                v-model="form1.product_category_id"
                placeholder="请选择拍品分类"
                clearable
                disabled
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in classifyOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="起拍价:" prop="price">
              <el-input
                v-model="form1.price"
                disabled
                class="input-spin"
                type="number"
              />
            </el-form-item>
            <el-form-item

              label="加价幅度:"
              disabled
              prop="add_money_range"
            >
              <el-input
                v-model="form1.add_money_range"
                class="input-spin"
                disabled
                type="number"
              />
            </el-form-item>
            <el-form-item label="估价:" prop="evaluation">
              <el-row>
                <el-col :span="11">
                  <el-input
                    disabled
                    v-model="form1.price"
                    class="input-spin"
                    type="number"
                  />
                </el-col>
                <el-col :span="2" style="text-align: center;">
                  -
                </el-col>
                <el-col :span="11">
                  <el-input
                    v-model="form1.max_money"
                    disabled
                    class="input-spin"
                    type="number"
                  />
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item

              label="拍卖场次:"
              disabled
              prop="auction_session_id"
            >
              <el-select
                v-model="form1.auction_session_id"
                placeholder="请选择拍卖场次"
                clearable
                disabled
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in fieldOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item> -->
            <el-form-item label="竞拍保证金:" prop="security_deposit">
              <el-input
                v-model="form1.security_deposit"
                disabled
                class="input-spin"
                type="number"
              /><span style="color: #aaa;">填“0”则不需要竞拍保证金</span>
            </el-form-item>
            <el-form-item label="拍品主图:" prop="image">
              <img
                style="width:148px;height:148px;display:inline-block;margin-right:8px;margin-bottom:8px"
                :src="form1.image"
              />
            </el-form-item>
            <el-form-item label="拍品图片:" prop="image">
              <!-- <el-upload
                :file-list="fileList"
                action="#"
                disabled
                accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                list-type="picture-card"
                :http-request="
                  file => {
                    return uploadImgHandle(file, 'from1');
                  }
                "
                :on-remove="
                  (file, fileList) => {
                    return removeHandle(file, fileList, 'from1');
                  }
                "
              >
                <i class="el-icon-plus"></i>
              </el-upload> -->
              <img
                v-for="(item, index) in fileList"
                :key="index"
                style="width:148px;height:148px;display:inline-block;margin-right:8px;margin-bottom:8px"
                :src="item.url"
              />
            </el-form-item>
            <el-form-item label="拍品参数:">
              <el-row>
                <el-col
                  v-for="(item, index) in form1._params"
                  :key="index"
                  :span="12"
                >
                  <!-- <el-input
                    v-model="item.value"
                    disabled
                    :placeholder="item.model"
                    :style="index > 1 ? 'margin-top: 10px;' : ''"
                  /> -->
                  {{ item.model }}：{{ item.value }}
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="拍品详情:">
              <div v-html="form1.content" />
            </el-form-item>
            <el-form-item label="店铺:">
              <el-input v-model.trim="form1.shopping_name" disabled />
            </el-form-item>
            <el-form-item label="保证金:">
              <el-input
                v-model.trim="form1.shopping_security_deposit"
                disabled
              />
            </el-form-item>
            <el-form-item label="创建时间:">
              <el-date-picker
                v-model="form1.created_at"
                disabled
                type="datetime"
                placeholder="选择创建时间"
                :clearable="false"
                style="width: 100%;"
              />
            </el-form-item>
            <el-form-item label="会员:">
              <el-input v-model.trim="form1.user_info" disabled />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div style="margin-top: 40px;text-align: center;">
        <el-button @click="dialogVisible1 = false">取消</el-button>
        <el-button type="danger" @click="handleSp">上拍</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getField,
  getClassify,
  getAuctionGoodWait,
  deleteAuctionGood,
  updateAuctionGood,
  uploadFile
} from "@/api/common";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Tinymce from "@/components/Tinymce";

export default {
  name: "AuctionGoodList",
  components: {
    Pagination,
    Tinymce
  },
  directives: {
    waves
  },
  data() {
    const validEvaluation = (value, callback, $msgForm, $userMsgForm) => {
      if (!$msgForm.min_money || !$msgForm.max_money) {
        callback(new Error("请输入估价"));
      } else if ($msgForm.min_money < 0) {
        callback(new Error("估价最小值不能小于0"));
      } else if ($msgForm.max_money <= 0) {
        callback(new Error("估价最大值必须大于0"));
      } else {
        callback();
      }
    };
    return {
      paramsNoSet: false,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      tabActive: 0,
      fieldOptions: undefined,
      classifyOptions: undefined,
      radioValue: "基础信息",
      dialogVisible: false,
      dialogVisible1: false,
      listQuery: {
        page: 1,
        per_page: 20,
        source: 1,
        type: undefined,
        name: undefined,
        product_category_id: undefined,
        auction_session_id: undefined,
        shopping_name: undefined,
        status: undefined,
        no: undefined,
        shopping: undefined
      },
      form: {},
      form1: {},
      fileList: [],
      rules: {
        name: [
          {
            required: true,
            message: "请输入拍品名称",
            trigger: "blur"
          }
        ],
        product_category_id: [
          {
            required: true,
            message: "请选择拍品分类",
            trigger: "change"
          }
        ],
        price: [
          {
            required: true,
            message: "请输入起拍价",
            trigger: "blur"
          }
        ],
        add_money_range: [
          {
            required: true,
            message: "请输入加价幅度",
            trigger: "blur"
          }
        ],
        evaluation: [
          {
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              validEvaluation(value, callback, this.form1, this.$refs.dataForm);
            }
          }
        ],
        auction_session_id: [
          {
            required: true,
            message: "请选择拍卖场次",
            trigger: "change"
          }
        ],
        security_deposit: [
          {
            required: true,
            message: "请输入竞拍保证金",
            trigger: "blur"
          }
        ],
        image_url: [
          {
            required: true,
            message: "请上传拍品图片",
            trigger: "change"
          }
        ]
      },
      paramsRules: {
        model: [
          {
            required: true,
            message: "请输入参数名称",
            trigger: "blur"
          }
        ],
        value: [
          {
            required: true,
            message: "请输入参数内容",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getFieldData();
    this.getClassifyData();
    this.getList();
  },
  methods: {
    addParam() {
      let param = {
        model: "",
        value: ""
      };
      this.form._params.push(param);
    },
    delParam(index) {
      this.form._params.splice(index, 1);
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    clearFilter() {
      this.listQuery["type"] = undefined;
      this.listQuery["name"] = undefined;
      this.listQuery["product_category_id"] = undefined;
      this.listQuery["auction_session_id"] = undefined;
      this.listQuery["shopping_name"] = undefined;
      this.listQuery["status"] = undefined;
      this.listQuery["no"] = undefined;
      this.listQuery["shopping"] = undefined;
      this.handleFilter();
    },
    inputChange(val) {
      if (this.listQuery.type == 0) {
        this.listQuery["shopping_name"] = undefined;
      } else {
        this.listQuery["shopping_name"] = val;
      }
    },
    inputChangeHandle() {
      if (this.listQuery.type == 0) {
        this.listQuery["shopping_name"] = undefined;
      } else {
        this.listQuery["shopping_name"] = this.listQuery.shopping;
      }
    },
    removeHandle(file, fileList, key) {
      this[key].image_url = fileList.length <= 0 ? undefined : "1";
      this.fileList = fileList;
    },
    uploadImgHandle(e, key) {
      const formData = new FormData();
      formData.append("file", e.file);
      uploadFile(formData).then(res => {
        const image = res.data;
        this.fileList.push({
          url: this.$store.state.settings.imgHost + image
        });
        this.$set(
          this[key],
          "image_url",
          this.$store.state.settings.imgHost + image
        );
      });
    },
    uploadOneImgHandle(e, key) {
      const formData = new FormData();
      formData.append("file", e.file);
      uploadFile(formData).then(res => {
        const image = res.data;
        this.$set(this[key], "image", image);
      });
    },
    tabChange(e) {
      this.tabActive = e;
    },
    handleSp() {
      this.$refs["postForm1"].validate(valid => {
        if (valid) {
          //   let params = {
          //     name: this.form1.name,
          //     product_category_id: this.form1.product_category_id.toString(),
          //     min_money: this.form1.min_money.toString(),
          //     image_list: this.fileList.map(res => {
          //       return res.url;
          //     }),
          //     order: this.form1.order.toString(),
          //     created_at: this.form1.created_at
          //   };
          //   if (this.form1._params && this.form1._params.length > 0) {
          //     let array = [];
          //     this.form1._params.forEach(res => {
          //       array.push({
          //         [res.model]: res.value
          //       });
          //     });
          //     params["params"] = array;
          //   }
          this.listLoading = true;
          updateAuctionGood(this.form1.id, { status: 1, audit_status: 2 })
            .then(() => {
              this.$notify({
                title: "提示",
                message: "操作成功",
                type: "success",
                duration: 2000
              });
              this.dialogVisible = false;
              this.getList();
            })
            .catch(() => {
              this.listLoading = false;
            });
        } else {
          this.$message.warning("还有必填项未填写");
        }
      });
    },
    handleSubmit() {
      console.log(this.form);
      this.$refs["postForm"].validate(valid => {
        if (valid) {
          const params = {
            image: this.form.image,
            name: this.form.name,
            product_category_id: this.form.product_category_id.toString(),
            min_money: this.form.min_money && this.form.min_money.toString(),
            image_list: this.fileList.map(res => {
              return res.url;
            }),
            order: this.form.order.toString(),
            created_at: this.form.created_at
          };
          if (this.form._params && this.form._params.length > 0) {
            this.paramsNoSet = false;
            const array = [];
            this.form._params.forEach(res => {
              array.push({
                [res.model]: res.value
              });
            });
            params["params"] = array;
          } else {
            this.paramsNoSet = true;
            return;
          }
          console.log(params);
          this.listLoading = true;
          updateAuctionGood(this.form.id, params)
            .then(() => {
              this.$notify({
                title: "提示",
                message: "操作成功",
                type: "success",
                duration: 2000
              });
              this.dialogVisible = false;
              this.getList();
            })
            .catch(() => {
              this.listLoading = false;
            });
        } else {
          this.radioValue = "基础信息";
          this.$message.warning("还有必填项未填写");
        }
      });
    },
    // 查看
    handleLook(row) {
      this.$router.push("/member/detail/" + row.id);
    },
    // 修改 || 上拍
    handleEdit(row, type) {
      console.log(row);
      this.fileList = [];
      this["form" + type].image_url = undefined;
      this["form" + type] = Object.assign({}, row);
      this["form" + type]["shopping_security_deposit"] =
        this["form" + type].shopping &&
        this["form" + type].shopping.security_deposit
          ? this["form" + type].shopping.security_deposit
          : "";
      this["form" + type]["shopping_name"] =
        this["form" + type].shopping &&
        this["form" + type].shopping.shopping_name
          ? this["form" + type].shopping.shopping_name
          : "";
      if (row.image_list && row.image_list != "null") {
        this.fileList = [];
        this["form" + type]["image_list"] = JSON.parse(
          this["form" + type]["image_list"]
        );
        if (this["form" + type]["image_list"].length > 0) {
          this["form" + type]["image_list"].forEach(res => {
            res = this.$store.state.settings.imgHost + res;
            this.fileList.push({
              url: res
            });
          });
          this["form" + type].image_url = 1;
        }
      } else {
        this["form" + type]["image_list"] = [];
      }
      if (this["form" + type].params && this["form" + type].params != "null") {
        this["form" + type]["params"] = JSON.parse(this["form" + type].params);
        if (this["form" + type].params.length > 0) {
          const array = [];
          this["form" + type].params.forEach(res => {
            for (const i in res) {
              array.push({
                model: i,
                value: res[i]
              });
            }
          });
          this.$set(this["form" + type], "_params", array);
        }
      }
      if (
        this["form" + type].user &&
        this["form" + type].user.name &&
        this["form" + type].user.user
      ) {
        this["form" + type]["user_info"] =
          this["form" + type].user.name +
          "(" +
          this["form" + type].user.user +
          ")";
      }
      this["dialogVisible" + type] = true;
      console.log(this["form" + type]);
      //   console.log(this.fileList);
    },
    handleUpdate(id, audit_status, status) {
      let msg = "您确认要上拍该拍品？";
      if (audit_status == "0") {
        msg = "您确认要下架该拍品？";
      }
      this.$confirm(msg, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          updateAuctionGood(id, {
            audit_status,
            status
          }).then(() => {
            this.$notify({
              title: "成功",
              message: "操作成功",
              type: "success",
              duration: 2000
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    getList() {
      this.listLoading = true;
      getAuctionGoodWait(this.listQuery)
        .then(response => {
          const { data, total } = response.data;
          this.list = data;
          this.total = total;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    getClassifyData() {
      getClassify().then(res => {
        this.classifyOptions = res.data;
      });
    },
    getFieldData() {
      getField({
        per_page: 100
      }).then(res => {
        this.fieldOptions = res.data.data;
      });
    },
    // 删除
    handleDelete(id) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          deleteAuctionGood(id)
            .then(() => {
              // 用于判断删除最后一页的所有数据，自动减少一页数据
              if (
                this.list.length == 1 &&
                this.listQuery.page > 1 &&
                this.listQuery.page >
                  parseInt((this.total - 1) / this.listQuery.per_page)
              ) {
                this.listQuery.page = this.listQuery.page - 1;
              }
              this.$notify({
                title: "提示",
                message: "删除成功",
                type: "success",
                duration: 2000
              });
              this.getList();
            })
            .catch(() => {
              this.listLoading = false;
            });
        })
        .catch(() => {});
    }
  }
};
</script>

<style>
.el-upload-list__item.is-ready,
.el-upload-list__item.is-uploading {
  display: none !important;
}

.hide .el-upload--picture-card {
  display: none;
}

.el-upload-list__item {
  transition: none !important;
}
.el-form-item-cust {
  display: flex;
  margin-bottom: 10px;
}
.el-form-item-cust .label {
  width: 90px;
  line-height: 36px;
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  font-weight: bold;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
.el-form-items {
  position: relative;
}
.el-form-item-cust .del {
  color: #f56c6c;
  cursor: pointer;
  padding-left: 10px;
  display: block;
  margin-top: 10px;
}
.el-form-item-cust .del::active {
  opacity: 0.8;
}
</style>
